package cn.yhsoft.fs;

import cn.hutool.core.io.FileUtil;
import lombok.var;

import java.io.InputStream;

/**
 * @author LiYong
 * 文件系统文件存储适配器
 */
public class FsFileSystemStorageAdapter implements FsStorageAdapter {
    private String basePath;

    public FsFileSystemStorageAdapter(String basePath) {
        if (!basePath.endsWith("/")) {
            basePath=basePath+"/";
        }
        this.basePath = basePath;
    }

    @Override
    public String save(String path, String saveFileName, InputStream fileInputStream) {
        path = path.startsWith("/") ? path.substring(1) : path;
        path = path.endsWith("/") ? path.substring(0, path.length() - 1) : path;
        var relativePath = path + "/" + saveFileName;
        var fullFileName = this.basePath + relativePath;
        var file = FileUtil.touch(fullFileName);
        FileUtil.writeFromStream(fileInputStream, file);
        return relativePath;
    }

    @Override
    public InputStream getInputStream(String path){
        var fullFileName = this.basePath + path;
        return FileUtil.getInputStream(fullFileName);
    }
}
